<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable @keyup.enter="handleQuery" style="width: 200px;">
          <el-option label="使用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="RefreshRight" @click="resetAndSearch">重置</el-button>
        <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增用户</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户列表表格 -->
    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column label="ID" align="center" prop="userId">
        <template #default="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username">
        <template #default="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话号码" align="center" prop="phoneNumber">
        <template #default="scope">
          <span>{{ scope.row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="email">
        <template #default="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密码" align="center" prop="passwordHash">
        <template #default="scope">
          <span>{{ scope.row.passwordHash }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册日期" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseDate(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" @change="(value) => handleStatusChange(scope.row.userId, value)" />
        </template>
      </el-table-column>
      <el-table-column label="上次登录时间" align="center" prop="lastLoginAt" width="180">
        <template #default="scope">
          <span>{{ parseDate(scope.row.lastLoginAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="note">
        <template #default="scope">
          <span>{{ scope.row.note }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)" style="margin-right: 10px;">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination v-show="total > 0" background layout="prev, pager, next" :total="total" v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" @current-change="handlePageChange" />
    </div>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue';
import { Search, RefreshRight, Plus } from '@element-plus/icons-vue';
import { ElMessage} from 'element-plus';
import { listUsers, getUsers, delUsers, addUsers, updateUsers, updateUserStatus } from "@/api/users";
import dayjs from 'dayjs';
import 'dayjs/locale/en'; // 引入英文语言包
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import customParseFormat from 'dayjs/plugin/customParseFormat';


// 配置 dayjs
dayjs.locale('en'); // 设置语言环境为英文
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);

// 响应式数据
const usersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    username: null,
    phoneNumber: null,
    email: null,
    password: null,
    note: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    username: null,
    status: null
  },
  rules: {
    username: [
      { required: true, message: "用户名不能为空", trigger: "blur" }
    ],
    phoneNumber: [
      { required: true, message: "电话号码不能为空", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" }
    ],
    passwordHash: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/**
 * 获取用户列表
 */
function getList() {
  loading.value = true;
  listUsers(queryParams.value)
    .then(response => {
      if (response.data && response.data.user && Array.isArray(response.data.user)) {
        usersList.value = response.data.user;
        total.value = response.data.total;
      } else {
        console.error('Invalid response format:', response);
        ElMessage.error('获取用户列表失败');
      }
    })
    .catch(error => {
      console.error('Failed to fetch user list:', error);
      ElMessage.error('获取用户列表失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 取消对话框并重置表单
 */
function cancel() {
  open.value = false;
  reset();
}

/**
 * 解析日期字符串
 * @param {string} dateString - 日期字符串
 * @returns {string} 格式化后的日期
 */
function parseDate(dateString) {
  const parsedDate = dayjs.tz(dateString, 'CST');
  if (!parsedDate.isValid()) {
    console.error('Failed to parse date:', dateString);
    return '无效日期';
  }
  return parsedDate.format('YYYY-MM-DD HH:mm:ss');
}

/**
 * 重置表单
 */
function reset() {
  form.value = {
    username: null,
    phoneNumber: null,
    email: null,
    password: null,
    note: null
  };
}

/**
 * 处理搜索查询
 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置查询条件
 */
function resetQuery() {
  queryParams.value.username = '';
  queryParams.value.status = null;
  usersList.value = []; // 清空用户列表
}

/**
 * 重置查询条件并重新获取列表
 */
function resetAndSearch() {
  resetQuery();
  getList();
}

/**
 * 处理表格行选择变化
 * @param {Array} selection - 选中的行数据
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/**
 * 打开新增用户对话框
 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户管理";
}

/**
 * 打开编辑用户对话框
 * @param {Object} row - 用户数据
 */
function handleUpdate(row) {
  const _userId = row.userId || ids.value;
  getUsers(_userId)
    .then(response => {
      form.value = { ...row };
      open.value = true;
      title.value = "修改用户管理";
    })
    .catch(error => {
      console.error('Failed to fetch user details:', error);
      ElMessage.error('获取用户详情失败');
    });
}

/**
 * 提交更新用户信息
 */
function submitUpdate() {
  const _userId = form.value.userId;
  updateUsers(form.value, _userId)
    .then(response => {
      if (response.code === 200) {
        ElMessage.success('更新用户信息成功');
        open.value = false;
        getList();  // 刷新用户列表
      }
    })
    .catch(error => {
      console.error('Failed to update user:', error);
      ElMessage.error('更新用户信息失败');
    });
}

/**
 * 提交表单（新增或修改用户）
 */
function submitForm() {
  if (title.value === "添加用户管理") {
    const userData = {
      username: form.value.username,
      password: form.value.password,
      email: form.value.email,
      phoneNumber: form.value.phoneNumber
    };

    addUsers(userData)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }
      })
      .catch(error => {
        console.error('Failed to add user:', error);
        ElMessage.error('新增用户失败');
      });
  } else {
    submitUpdate(form.value)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success("修改成功");
          open.value = false;
          getList();  // 刷新用户列表
        }
      })
      .catch(error => {
        console.error('Failed to update user:', error);
        ElMessage.error('修改用户失败');
      });
  }
}

/**
 * 处理删除用户
 * @param {Object} row - 用户数据
 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value;
  delUsers(_userIds)
    .then(response => {
      if (response.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    })
    .catch(error => {
      console.error('Failed to delete user:', error);
      ElMessage.error('删除用户失败');
    });
}

/**
 * 处理用户状态变化
 * @param {number} userId - 用户ID
 * @param {number} status - 用户状态
 */
function handleStatusChange(userId, status) {
  updateUserStatus(userId, { status })
    .then(response => {
      if (response.code === 200) {
        ElMessage.success("用户状态更新成功");
        getList();
      }
    })
    .catch(error => {
      console.error('Failed to update user status:', error.response?.data || error.message);
      ElMessage.error('用户状态更新失败');
    });
}

/**
 * 处理分页变化
 * @param {number} page - 当前页码
 */
function handlePageChange(page) {
  queryParams.value.pageNum = page;
  getList();
}

// 初始化获取用户列表
getList();
</script>
//分页置于右下角
<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>